
var gameInfo = require("gameStrategy");
var GameState = require("gameState");
var playerManager = require("playerManager");

var net = require("net")

/**
 * 游戏状态
 */
var _playerState = cc.Enum({
  NORMAL: 0,  //普通状体
  SUPER: 1, //超级变身状体
});

var isConnectServer = true
var nickName = "hhaah"
var maxScore = 0
var avatarUrl

var gameManager = cc.Class({
  extends: cc.Component,

  properties: {
    playerManager: {
      default: null,
      type: cc.Node
    },
    roadblockManager: {
      default: null,
      type: cc.Node
    },
    sceneManager: {
      default: null,
      type: cc.Node
    },
    baseScoreNode: {
      default: null,
      type: cc.Node
    },
    magicScoreNode: {
      default: null,
      type: cc.Node
    },
    runningNode: {
      default: null,
      type: cc.Node
    },
    StartUiPrefab: {
      default: null,
      type: cc.Prefab
    },
    gameResultUiPrefab: {
      default: null,
      type: cc.Prefab
    },
    gameRankUiPrefab: {
      default: null,
      type: cc.Prefab
    },
    superTimeNode: {
      default: null,
      type: cc.Node
    },
    BeiJingSource: {
      type: cc.AudioSource,
      default: null
    },
    ShiBaiSource: {
      url: cc.AudioClip,
      default: null
    },
    redHeartDestroySelfPrefab: {
      default: null,
      type: cc.Prefab
    },
  },

  statics: {
    instance: null
  },

  // use this for initialization
  onLoad: function () {
    var imageName = localStorage.getItem("imageName");
    var self = this;
    net.loginServer(
      function (isSuc, response) {
        if (isSuc) {
          console.log("-----登录成功-----response:" + JSON.stringify(response));
          wx.showShareMenu();
          //监听右上角的分享调用
          cc.loader.loadRes("image/share", function (err, data) {
            wx.onShareAppMessage(function (res) {
              console.log("url !!! : ",data.url)
              return {
                title: "是兄弟，就来砍我啊!!",
                imageUrl: "res/raw-assets/resources/image/" + imageName + ".jpg",
                success(res) {
                  console.log("转发成功!!!")
                  common.diamond += 20;
                },
                fail(res) {
                  console.log("转发失败!!!")
                }
              }
            })
          });
        } else {
          console.log("登录服务器失败！")
        }
        self.startGame();
      }
    )
  },

  startGame: function () {
    console.log("-----startGame-----");

    gameManager.instance = this;

    var screen = cc.view.getVisibleSize();
    this.sceneWidth = screen.width;
    this.sceneHeight = screen.height;
    this.intervalTime = 0;
    this.totalTime = 0;
    this.state = GameState.STOP;
    this.playerManagerSc = this.playerManager.getComponent("playerManager");
    this.sceneManagerSc = this.sceneManager.getComponent("sceneManager");
    this.roadblockManagerSc = this.roadblockManager.getComponent("roadblockManager");

    this.playerState = _playerState.NORMAL;
    this.baseScore = 0;
    this.magicScore = 0;
    this.superStateContinueTime = 0;

    //UI相关
    this.baseScoreSc = this.baseScoreNode.getComponent("baseScore");
    this.magicScoreSc = this.magicScoreNode.getComponent("magicScore");
    var superTimeTxtNode = this.superTimeNode.getChildByName("SuperTimeTxt");
    this.superTimeTxtSc = superTimeTxtNode.getComponent("superTimeTxt");

    this.returnToStartUi();

    //是否新手引导
    this.isGuideUi = true;

    cc.game.setFrameRate(100);
  },

  // called every frame
  update: function (dt) {
    if (this.state != GameState.RUNNING) {
      return;
    }

    if (this.playerState == _playerState.SUPER) {
      this.superStateContinueTime += dt;
      //变身时间是否结束，增加0.5秒，为了显示倒计时的0.
      if (this.superStateContinueTime >= gameInfo.gameRunInfo.superStateContinueTime+0.5) {
        this.superStateContinueTime = 0;
        this.changePlayerStateNormal();
      }
    }
    else {
      this.totalTime += dt;
      this.intervalTime += dt;
      if (this.intervalTime > this.currentStageInfo.Time) {
        this.gotoNextStage();
        this.intervalTime = 0;
      }
    }
  },

  gotoNextStage: function () {
    if (this.currentStage < gameInfo.gameCfgs.length - 1) {
      this.currentStage++;
    }

    this.switchStageInfo();

    this.updateEntityData();
  },

  switchStageInfo: function () {
    cc.log("切换到第 " + this.currentStage + " 阶段");
    this.currentStageInfo = gameInfo.gameCfgs[this.currentStage];
    cc.log(this.currentStageInfo);
  },

  // 更新节点数据
  updateEntityData: function () {
    cc.log("game manager updateEntityData");
    var speed = this.getCurrenSpeed();
    this.playerManagerSc.setSpeed(speed);
    this.sceneManagerSc.setSpeed(speed);
    this.roadblockManagerSc.setSpeed(speed);
    this.playerManagerSc.setStageInfo(this.currentStageInfo);
    this.sceneManagerSc.setStageInfo(this.currentStageInfo);
    this.roadblockManagerSc.setStageInfo(this.currentStageInfo);
  },

  // 开始
  running: function () {
    nickName = localStorage.getItem("nickName");
    avatarUrl = localStorage.getItem("avatarUrl");

    cc.log("game manager running");
    this.runningNode.active = true;

    this.currentStage = 0;
    this.switchStageInfo();
    this.state = GameState.RUNNING;

    this.baseScore = 0;
    this.magicScore = 0;
    this.baseScoreSc.updateBaseScore(this.baseScore);
    this.magicScoreSc.updateBaseScore(this.magicScore);

    var speed = this.getCurrenSpeed();
    this.playerManagerSc.running(speed);
    this.sceneManagerSc.running(speed);
    this.roadblockManagerSc.running(speed);

    this.updateEntityData();

    this.BeiJingSource.play();
  },

  // 暂停
  pause: function () {
    cc.log("game manager pause");
    this.state = GameState.PAUSE;
    this.playerManagerSc.pause();
    this.sceneManagerSc.pause();
    this.roadblockManagerSc.pause();
  },

  // 恢复
  continue: function () {
    cc.log("game manager continue");
    this.state = GameState.RUNNING;
    this.playerManagerSc.continue();
    this.sceneManagerSc.continue();
    this.roadblockManagerSc.continue();
  },

  // 停止
  stop: function () {
    cc.log("game manager stop");

    this.state = GameState.STOP;
    this.playerManagerSc.stop();
    this.sceneManagerSc.stop();
    this.roadblockManagerSc.stop();

    this.BeiJingSource.stop();
  },

  getCurrenSpeed: function () {
    return this.currentStageInfo.Speed;
  },

  // 设置速度倍数,power:倍数
  changeGameSpeed: function (power) {
    var speed = this.getCurrenSpeed() * power;
    this.playerManagerSc.setSpeed(speed);
    this.sceneManagerSc.setSpeed(speed);
    this.roadblockManagerSc.setSpeed(speed);
  },

  // 恢复游戏速度到默认
  recoverGameSpeed: function (power) {
    var speed = this.getCurrenSpeed();
    this.playerManagerSc.setSpeed(speed);
    this.sceneManagerSc.setSpeed(speed);
    this.roadblockManagerSc.setSpeed(speed);
  },

  //上传成绩 距离 撞击次数 成绩
  sendScore: function () {
    // 测试分数上传
    var distance = this.baseScore;
    var hitCount = this.baseScore;
    var score = this.baseScore;
    var self = this;
    net.uploadScore(distance, hitCount, score,
      function (isSuc, response) {
        if (isSuc) {
          console.log("-----上传分数成功-----response:" + JSON.stringify(response));
          //maxScore = response.score
          if (response.errCode == 0) {
            var scoreReplys = response.scoreReplys
            self.gameFinished(scoreReplys)
          }
        } else {
          console.log("上传分数失败！")
          self.scheduleOnce(self.gameFinished, 2);
        }
      }
    )
  },

  // 障碍快撞击后，增加、减少分数
  addScore: function (score, magicScore, isBlock) {
    if (isBlock && this.playerState == _playerState.NORMAL) {
      cc.log("碰到障碍快，游戏结束！");
      this.stop();
      // this.playerManagerSc.playerDie();
      this.sendScore();
      //this.scheduleOnce(this.gameFinished, 2);
      //roadblock.destroy();
      return;
    }

    //普通模式下
    if (this.playerState == _playerState.NORMAL) {
      this.baseScore += score;//gameInfo.gameRunInfo.baseScoreChange;
      this.magicScore += magicScore;//gameInfo.gameRunInfo.baseMagicChange;
      if (this.magicScore >= gameInfo.gameRunInfo.superMagicMax) {
        this.changePlayerStateSuper();
      }
      cc.log("[normal state] game score: " + this.baseScore + " ,magicScore: " + this.magicScore);
    }
    else {
      this.baseScore += gameInfo.gameRunInfo.baseScoreChange * gameInfo.gameRunInfo.superStateScoreRate;
      cc.log("[super state] game score: " + this.baseScore + " ,magicScore: " + this.magicScore);
    }

    this.baseScoreSc.updateBaseScore(this.baseScore);
    this.magicScoreSc.updateBaseScore(this.magicScore);

    //飞金币动画  todo:性能消耗
    var redHeartDestroySelfNode = cc.instantiate(this.redHeartDestroySelfPrefab);
    redHeartDestroySelfNode.active = true;
    redHeartDestroySelfNode.parent = this.node;
    var redHeartDestroySelfSc = redHeartDestroySelfNode.getComponent("redHeartDestroySelf");
    //位置左上偏移一段距离
    redHeartDestroySelfSc.initData(this.playerManager.x - 50, this.playerManager.y + 50);
  },

  changePlayerStateNormal: function () {
    cc.log("[recoverGameSpeed] game score: " + this.baseScore + " ,magicScore: " + this.magicScore);
    this.playerState = _playerState.NORMAL;
    this.recoverGameSpeed();
    this.playerManagerSc.changePlayerStateNormal();
    this.superTimeTxtSc.changePlayerStateNormal();
    this.magicScoreSc.changePlayerStateNormal();
  },

  changePlayerStateSuper: function () {
    cc.log("[changePlayerStateSuper] game score: " + this.baseScore + " ,magicScore: " + this.magicScore);
    this.playerState = _playerState.SUPER;
    this.superStateContinueTime = 0;
    this.magicScore = 0;
    this.changeGameSpeed(gameInfo.gameRunInfo.superStateSpeedRate);
    this.playerManagerSc.changePlayerStateSuper();
    this.superTimeTxtSc.changePlayerStateSuper(gameInfo.gameRunInfo.superStateContinueTime);
    this.magicScoreSc.changePlayerStateSuper();
  },

  isSuperState: function () {
    return this.playerState == _playerState.SUPER;
  },

  returnToStartUi: function () {
    this.currentMainUi = cc.instantiate(this.StartUiPrefab);
    this.currentMainUi.parent = this.node;
    this.currentMainUi.active = true;

    this.subscriberStartButtonEvent();
    this.subscriberRankButtonEvent();

    this.runningNode.active = false;
  },

  returnToGameResultUi: function (scoreReplys) {
    this.currentMainUi = cc.instantiate(this.gameResultUiPrefab);
    this.currentMainUi.parent = this.node;
    this.currentMainUi.active = true;

    this.subscriberStartButtonEvent();
    this.subscriberRankButtonEvent();

    var resultUiCtrlSc = this.currentMainUi.getComponent("resultUiCtrl");
    resultUiCtrlSc.updateBaseScore(this.baseScore, scoreReplys);

    this.runningNode.active = false;

    //结算时的声音
    cc.audioEngine.play(this.ShiBaiSource, false, 1);
  },

  returnToGameRankUi: function (scoreReplys) {
    this.currentMainUi = cc.instantiate(this.gameRankUiPrefab);
    this.currentMainUi.parent = this.node;
    this.currentMainUi.active = true;

    this.subscriberStartButtonEvent();

    var rankUiCtrlSc = this.currentMainUi.getComponent("rankUiCtrl");
    rankUiCtrlSc.updateBaseScore(scoreReplys);

    this.runningNode.active = false;
  },

  //订阅游戏开始按钮事件
  subscriberStartButtonEvent: function () {
    var currentButtonNode = this.currentMainUi.getChildByName("StartButton");
    var buttonSc = currentButtonNode.getComponent(cc.Button);
    var eventHandler = new cc.Component.EventHandler();
    eventHandler.target = this.node;
    eventHandler.component = "gameManager";
    eventHandler.handler = "onStartButtonClicked"
    buttonSc.clickEvents[0] = eventHandler;
  },

  //订阅游戏全局排行榜按钮事件
  subscriberRankButtonEvent: function () {
    var currentButtonNode = this.currentMainUi.getChildByName("RankButton");
    var buttonSc = currentButtonNode.getComponent(cc.Button);
    var eventHandler = new cc.Component.EventHandler();
    eventHandler.target = this.node;
    eventHandler.component = "gameManager";
    eventHandler.handler = "onRankButtonClicked"
    buttonSc.clickEvents[0] = eventHandler;
  },

  //游戏开始按钮点击
  onStartButtonClicked: function () {
    if (this.state == GameState.RUNNING) {
      cc.log("game manager stop");
      this.stop();
      cc.director.getCollisionManager().enabled = false;
      // cc.director.getCollisionManager().enabledDebugDraw = false;
    }
    else {
      cc.log("game manager running");
      // this.running();

      if (this.isGuideUi) {
        this.isGuideUi = false;
        //延迟开始游戏
        this.playerManagerSc.prepareRunning();
        this.scheduleOnce(this.delayRunning, 2);
      } else {
        this.running();
      }


      cc.director.getCollisionManager().enabled = true;
      // cc.director.getCollisionManager().enabledDebugDraw = true;
      if (this.currentMainUi != null) {
        cc.log("destory start Ui");
        this.currentMainUi.destroy();
        this.currentMainUi = null;
      } else {
        cc.error("onStartButtonClicked find error. find startui is null");
      }
    }
  },

  delayRunning: function () {
    this.running();
  },

  //游戏排行榜按钮点击
  onRankButtonClicked: function () {
    if (this.currentMainUi != null) {
      cc.log("destory startButtonNode Ui");
      this.currentMainUi.destroy();
      this.currentMainUi = null;
    } else {
      cc.error("onStartButtonClicked find error. find startButtonNode is null");
    }
    var self = this;
    net.getRankList(0,
      function (isSuc, response) {
        if (isSuc) {
          console.log("-----拉取最高分成功-----response:" + JSON.stringify(response));
          if (response.errCode == 0) {
            var scoreReplys = response.scoreReplys
            self.returnToGameRankUi(scoreReplys);
          }
        } else {
          console.log("拉取最高分失败")
          self.returnToGameRankUi(null);
        }
      }
    )
    //
  },


  gameFinished: function (scoreReplys) {
    this.stop();
    this.returnToGameResultUi(scoreReplys);
  },

});

